// component/choose-spec-dialog/choose-spec.js
const app = getApp();
const api = require("../../server/Api.js")
Component({
  options: {
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */

  properties: {
    goods: Object,
    buyType: Number
  },

  /**
   * 组件的初始数据
   */
  data: {
    selectMode: "默认"
  },

  /**
   * 组件的方法列表
   */
  methods: {
    hiddenDialog: function() {
      this.triggerEvent('hiddenDialog')
    },
    //规格选择
    onModeTypeIndex: function(e) {
      this.setData({
        selectMode: e.currentTarget.id
      })
    },
    lower_count: function() {
      if (this.data.goods.goodsQuantity > 1) {
        this.data.goods.goodsQuantity = this.data.goods.goodsQuantity - 1;
        this.setData({
          goods: this.data.goods
        })
      }
    },
    upper_count: function() {
      this.data.goods.goodsQuantity = this.data.goods.goodsQuantity + 1;
      this.setData({
        goods: this.data.goods
      })
    },
    addCart: function() {
      let userBean = app.globalData.userBean;
      if (!userBean || !userBean.consumerId) {
        tt.navigateTo({
          url: '../login/login',
        })
      }

      let that = this;
      //服务器加入购物车
      let skuId = that.data.goods.skuId || that.data.goods.skuid;
      let userId = app.globalData.userBean.consumerId;
      if (that.data.buyType == 0) {
        if (that.data.goods.receiptInterval != 1) {
          app.showToast("该商品不支持加上购物车")
          return;
        }
        api.addCart(that.data.goods.goodsQuantity, skuId, userId).then(res => {
          that.triggerEvent('refreshCart', {
            skuId: skuId,
            goods: that.data.goods
          })
        }).catch(msg => {
          let message = typeof msg == "string" ? msg : msg.message;
          app.showToast(message)
        })
      } else {
        let checkedItems = [];
        console.log(that.data.goods);
        checkedItems.push({
          goodsQuantity: that.data.goods.goodsQuantity,
          spuTitle: that.data.goods.title,
          spuExtendSpec: {
            spec1: {
              spec_name: "默认"
            }
          },
          skuImage: that.data.goods.images[0].url,
          goodsPrice: that.data.goods.minPrice,
          spuId: that.data.goods.spuId,
          skuId: that.data.goods.skuId,
          storeId: that.data.goods.storeId
        });
        let itemsJson = JSON.stringify(checkedItems);
        itemsJson = itemsJson.replace(/\?/g, "-|-").replace(/\=/g, "-||-");
        tt.redirectTo({
          url: '../cart-confirm-order/cart-confirm-order?items=' + itemsJson + "&type=" + that.data.buyType,
          success() {
            that.triggerEvent('hiddenDialog');
          }
        })
      }
    }
  }
})